#include <myhead.h>
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>

//定义库存
int top=0;
//1、创建互斥锁
pthread_mutex_t mtu;
//11、创建无名信号量
sem_t sem;
//11、创建条件变量
pthread_cond_t cond;
//
void*test1(void*arg);//生产者
void*test2(void*arg);//消费者
int main(int argc,const char*argv[])
{
	//初始化
	pthread_mutex_init(&mtu,NULL);
	sem_init(&sem,0,0);
	pthread_cond_init(&cond,NULL);
	pthread_t p1,p2,p3,p4;
	if(pthread_create(&p1,NULL,test1,NULL)!=0){printf("创建失败\n");return -1;}
	if(pthread_create(&p2,NULL,test2,NULL)!=0){printf("创建失败\n");return -1;}
	if(pthread_create(&p3,NULL,test2,NULL)!=0){printf("创建失败\n");return -1;}
	if(pthread_create(&p4,NULL,test2,NULL)!=0){printf("创建失败\n");return -1;}
	//
	//
	//销毁
	pthread_mutex_destroy(&mtu);
	sem_destroy(&sem);
	pthread_cond_destroy(&cond);
	//
	//
	//回收线程
	pthread_join(p1,NULL);
	pthread_join(p2,NULL);
	pthread_join(p3,NULL);
	pthread_join(p4,NULL);

	return 0;
}
void*test1(void*arg)
{
	//int top=*(int *)arg;
	int n=5;
	while(n--)
	{
		sleep(2);
		printf("当前库存%d\n",top);
		sleep(3);
		top+=3;
		printf("生产了三辆，库存%d\n\n",top);
		sem_post(&sem);
		sem_post(&sem);
		sem_post(&sem);
		pthread_cond_broadcast(&cond);
	}
	return NULL;
}
void*test2(void*arg)
{
	//int top=*(int *)arg;
	int n=5;
	while(n--)
	{
		pthread_mutex_lock(&mtu);
		pthread_cond_wait(&cond,&mtu);
		sem_wait(&sem);
		sem_wait(&sem);
		top-=2;
		printf("消费了两辆，库存%d\n",top);
		pthread_mutex_unlock(&mtu);
	}
}
